<template>
  <PlusDialogForm
    ref="formRef"
    v-model:visible="visible"
    v-model="form"
    :form="{
      columns,
      labelWidth: 100,
      labelPosition: 'right'
    }"
    :dialog="{ title: '用户设置', confirmLoading: loading }"
    @confirm="submit"
  >
    <template #plus-field-warehouseId>
      <k-select-http
        v-if="visible"
        v-model="form.warehouseId"
        paramsKey="searchValue"
        :immediately="true"
        :httpfn="getWarehouseList"
        :keyprops="{ label: 'name', value: 'warehouseId' }"
        @change="changeWarehouseId"
      />
    </template>
    <template #plus-field-deptId>
      <el-cascader
        v-if="visible && form.warehouseId"
        v-model="form.deptId"
        :options="deptList"
        :props="popsSetting"
        style="width: 100%"
      />
    </template>
  </PlusDialogForm>
</template>
<script setup lang="ts">
import { ref, nextTick, computed, watch } from "vue";
import { ElMessage } from "element-plus";

import {
  type PlusColumn,
  PlusDialogForm,
  type FieldValues
} from "plus-pro-components";

import kSelectHttp from "@/components/k-select-http/index.vue";
import { allListApi as getWarehouseList } from "@/api/warehouse";
import { allListApi as getDeptsListApi } from "@/api/system/dept";
import { editApi } from "@/api/system/user";

const columns: PlusColumn[] = [
  {
    label: "账号",
    prop: "userName",
    rules: { required: true, message: "请输入账号", trigger: "blur" }
  },
  {
    label: "用户名称",
    prop: "nickName",
    rules: { required: true, message: "请输入用户名称", trigger: "blur" }
  },
  {
    label: "角色",
    prop: "roleName",
    valueType: "text"
  },
  {
    label: "工具室",
    prop: "warehouseId",
    rules: {
      required: true,
      message: "请选择工具室",
      trigger: "change"
    }
  },
  {
    label: "组织",
    prop: "deptId",
    // valueType: "cascader",
    hideInForm: computed(() => {
      return form.value.warehouseId ? false : true;
    }),
    rules: { required: true, message: "请选择组织", trigger: "change" }
    /* fieldProps: computed(() => ({
      props: {
        checkStrictly: false, // 是否每一层可选
        label: "deptName",
        value: "deptId",
        children: "childDeptVos"
      }
    })),
    options: computed(() => {
      return deptList.value;
    }) */
  }
];
const popsSetting = {
  label: "deptName",
  value: "deptId",
  children: "childDeptVos",
  checkStrictly: false
};
const initForm = (formdata = {} as any) => {
  const data = {
    roleName: "管理员",
    password: "",
    checkpass: "",
    warehouseId: "",
    deptId: [],
    userName: "",
    nickName: "",
    userId: ""
  };
  for (const key in data) {
    if (formdata[key]) {
      data[key] = formdata[key];
    }
  }
  if (formdata.depts) {
    data.deptId = formdata.depts.map(item => item.deptId);
  }
  // console.log(data.deptId);
  return data;
};
const form = ref(initForm());

const visible = ref(false);
const formRef = ref(null);
const show = (formdata = {} as any) => {
  visible.value = true;
  nextTick(() => {
    formRef?.value?.formInstance?.clearValidate();
    form.value = initForm(formdata);
  });
  getDeptsList(formdata.warehouseId, () => {});
};
defineExpose({ show });

const loading = ref(false);
const emit = defineEmits(["confirm"]);

const submit = () => {
  const { deptId, userName, nickName, warehouseId, userId } = form.value;
  const params = {
    deptId: deptId[deptId.length - 1],
    userName,
    nickName,
    warehouseId,
    status: 0,
    userId
  };

  editApi(params)
    .then(res => {
      loading.value = false;
      ElMessage.success("设置用户成功");
      emit("confirm", [{ ...params, userId: res.data }]);
      visible.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

/* 组织相关 */
const deptList = ref([]);
const getDeptsList = async (warehouseId, callback?) => {
  // console.log(1);
  const res = await getDeptsListApi({ warehouseId });
  deptList.value = res.data as any[];
  callback && callback();
};

const changeWarehouseId = val => {
  // console.log(2);
  form.value.deptId = [];
  getDeptsList(val);
};
</script>
